﻿namespace SubhadraSolutions.Sharp.Utils.Windows
{
    using System;
    using System.Windows.Forms;

    using SubhadraSolutions.Sharp.Utils.Threading;
    using SubhadraSolutions.Sharp.Utils.Validation;

    /// <summary>
    /// The ControlInvokeDispatcher class.
    /// </summary>
    public class ControlInvokeDispatcher : IDispatcher
    {
        /// <summary>
        /// The control reference
        /// </summary>
        private readonly WeakReference controlReference;

        /// <summary>
        /// Initializes a new instance of the <see cref="ControlInvokeDispatcher"/> class.
        /// </summary>
        /// <param name="control">The control.</param>
        public ControlInvokeDispatcher(Control control)
        {
            Guard.ArgumentNotNull(control, "control");
            this.controlReference = new WeakReference(control);
        }

        /// <summary>
        /// Dispatches the specified action.
        /// </summary>
        /// <param name="action">The action.</param>
        public void Dispatch(Action action)
        {
            var control = this.controlReference.Target as Control;
            if (control != null)
            {
                control.Invoke(action);
            }
        }
    }
}
